package samsung.entities;

import samsung.exceptions.BrokenCountryBorderException;
import samsung.exceptions.NotConnectedCountriesException;
import samsung.exceptions.OutOfBorderException;
import samsung.exceptions.WrongCountryInfoException;
import samsung.other.CountryArea;
import samsung.other.CountryInfoParser;
import samsung.other.Reader;

/**
 * Class need to construct <code>Area</code> object.
 *
 * @author Vitaliy Muzalevskiy
 */
public class AreaBuilder {

    private CountryBuilder builder = new CountryBuilder();
    protected Reader reader = new Reader();

    /**
     * Method control by process of
     * <code>Area</code> object construction.
     *
     * @param countriesNumber - number of countries in current area.
     * @return constructed <code>Area</code> object.
     * @throws NotConnectedCountriesException - if countries in current area are
     * not connected to each other.
     * @throws BrokenCountryBorderException - if some countries in current area
     * have the same parts.
     */
    public Area buildArea(int countriesNumber)
            throws NotConnectedCountriesException, BrokenCountryBorderException {
        Area result = new Area();
        Country country;
        for (int i = 0; i < countriesNumber; i++) {
            String countryInfo = readCountryInfo();
            try {
                String name = CountryInfoParser.getCountryName(countryInfo);
                CountryArea countryArea = CountryInfoParser.getCountryArea(countryInfo);
                country = builder.buildCountry(countryArea, name);
                result.addCountry(country);
            } catch (WrongCountryInfoException e) {
                System.err.println("Error during entering the information about"
                        + "country. Enter country information once more.");
                i--;
            } catch (OutOfBorderException ex) {
                System.err.println("Cuntry with such parameters can`t be added"
                        + "to current area. Enter new parameters for the country");
                i--;
            }
        }
        result.prepareMembersToWork();
        result.checkAreaOnCountryConnections();        
        return result;
    }
    
    /**
     * Method need to read information about country from console.
     *
     * @return <code>String</code> value that contains needed parameters for 
     *      country constructing.
     */
    public String readCountryInfo(){
        return reader.readCountryInfo();
    }
}
